//
//  DownLoadViewController.m
//  HeartOfMeet
//
//  Created by qianfeng on 16/4/9.
//  Copyright © 2016年 千云锋. All rights reserved.
//

#import "DownLoadViewController.h"

@interface DownLoadViewController ()<UITableViewDelegate,UITableViewDataSource>

@property (nonatomic,strong)NSOperationQueue *queue;

@property (nonatomic,strong) UIBarButtonItem *leftBarButtonItem1;
@property (nonatomic,strong) UIBarButtonItem *leftBarButtonItem2;


@end

@implementation DownLoadViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationController.navigationBar.tintColor = [UIColor whiteColor];
    self.view.backgroundColor = [UIColor blackColor];
    self.title = @"我的下载";
    
//    self.dataArray = [[NSMutableArray alloc] initWithArray:[DownLoadModel MR_findAll]];
    
    self.queue = [[NSOperationQueue alloc] init];
    
    if (self.timer == nil) {
        self.timer = [NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(update) userInfo:nil repeats:YES];
        [self.timer setFireDate:[NSDate distantPast]];
    }
    
    self.leftBarButtonItem1 = [[UIBarButtonItem alloc] initWithImage:[[[UIImage imageNamed: @"white_back"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    
    self.leftBarButtonItem2 = [[UIBarButtonItem alloc] initWithImage:[[[UIImage imageNamed: @"down_big"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(downLoadAll)];
    self.navigationItem.leftBarButtonItems = @[self.leftBarButtonItem1,self.leftBarButtonItem2];
    
    UIBarButtonItem *rightBarButtonItem1 = [[UIBarButtonItem alloc] initWithImage:[[[UIImage imageNamed: @"yinle_"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(pushPlayer)];
    
    self.rightBarButtonItem2 = [[UIBarButtonItem alloc] initWithImage:[[[UIImage imageNamed: @"delete_"] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] imageWithRenderingMode:UIImageRenderingModeAlwaysOriginal] style:UIBarButtonItemStylePlain target:self action:@selector(delete:)];
    
    self.navigationItem.rightBarButtonItems = @[rightBarButtonItem1,self.rightBarButtonItem2];
}

- (void)back{
    [self dismissViewControllerAnimated:YES completion:nil];
    [self cancelClick];
}

- (void)pushPlayer{
    [UIView  beginAnimations:nil context:NULL];
    [UIView setAnimationCurve:UIViewAnimationCurveEaseInOut];
    [UIView setAnimationDuration:0.25];
    [UIView setAnimationTransition:UIViewAnimationTransitionFlipFromLeft forView:self.navigationController.view cache:NO];
    [UIView commitAnimations];
    
    [UIView beginAnimations:nil context:NULL];
    [UIView setAnimationDelay:0.1];
    [self.navigationController pushViewController:[PlayerViewController sharePlayer] animated:NO];
    [UIView commitAnimations];
    
    [self cancelClick];
}

+ (UINavigationController *)shareDownLoad{
    static UINavigationController *nav;
    if (nav == nil) {
        nav = [[UINavigationController alloc] initWithRootViewController:[[self class] shareDownLoadVC]];
        
    }
    return nav;
}

+ (DownLoadViewController *)shareDownLoadVC{
    static DownLoadViewController *dovc;
    if (dovc == nil) {
        dovc = [[[self class] alloc] init];
        dovc.downLoadQueArray = [[NSMutableArray alloc] init];
    }
    return dovc;
}

- (void)update{
//    self.dataArray = [[NSMutableArray alloc] initWithArray:[DownLoadModel MR_findAll]];
    [self.tableView reloadData];
}

- (void)viewWillAppear:(BOOL)animated{
    [self.timer setFireDate:[NSDate distantPast]];
}

- (void)viewWillDisappear:(BOOL)animated{
    [self.timer setFireDate:[NSDate distantFuture]];
}

- (void)downLoadAll{
//    for (BreakPointDownload *model in self.downLoadQueArray) {
//        [model stopDownload];
//        [model breakPointDownLoadDataWithUrl:model.needDownLoadUrl downloadProcess:^(BreakPointDownload *download) {
//            NSArray *arr = [DownLoadModel MR_findByAttribute:@"currentMp3Url" withValue:model.needDownLoadUrl];
//            
//            DownLoadModel *downLoadModel = arr[0];
//            downLoadModel.loadedSize = [[NSNumber alloc] initWithDouble:download.loadedSize/1024.0/1024.0];
//            downLoadModel.fileSize = [[NSNumber alloc] initWithDouble:download.fileSize/1024.0/1024.0];
//            
//            [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
//        }];
//    }
}

- (void)downLoadWithModel:(DownLoadModel *)model{
    BreakPointDownload *download = [[BreakPointDownload alloc] init];
    download.needDownLoadUrl = model.currentMp3Url;
    
    [self.downLoadQueArray addObject:download];
//    
//    [download breakPointDownLoadDataWithUrl:download.needDownLoadUrl downloadProcess:^(BreakPointDownload *download) {
//        NSArray *arr = [DownLoadModel MR_findByAttribute:@"currentMp3Url" withValue:model.currentMp3Url];
//        if (arr.count == 0) {
//            return ;
//        }
//        DownLoadModel *downLoadModel = arr[0];
//        downLoadModel.loadedSize = [[NSNumber alloc] initWithDouble:download.loadedSize/1024.0/1024.0];
//        downLoadModel.fileSize = [[NSNumber alloc] initWithDouble:download.fileSize/1024.0/1024.0];
    
//        [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
//    }];
}

//编辑按钮
- (void)delete:(UIBarButtonItem *)item{
    [self.timer setFireDate:[NSDate distantFuture]];
    
    self.rightBarButtonItem2.enabled = NO;
    
    self.tableView.allowsMultipleSelectionDuringEditing = YES;
    self.tableView.allowsSelectionDuringEditing = YES;
    [self.tableView setEditing:YES animated:YES];
    
    CGFloat y = self.view.bounds.size.height-39;
    [UIView animateWithDuration:0.2 animations:^{
        self.editView.frame = CGRectMake(0, y, self.view.bounds.size.width, 39);
    }];
}

//取消
- (void)cancelClick{
    [self.timer setFireDate:[NSDate distantPast]];
    
    self.tableView.allowsMultipleSelectionDuringEditing = NO;
    self.tableView.allowsSelectionDuringEditing = NO;
    [self.tableView setEditing:NO animated:YES];
    
    CGFloat y = self.view.bounds.size.height;
    [UIView animateWithDuration:0.2 animations:^{
        self.editView.frame = CGRectMake(0, y, self.view.bounds.size.width, 35);
    }];
    self.rightBarButtonItem2.enabled = YES;
}
//删除
- (void)deleteClick{
    [self.timer setFireDate:[NSDate distantPast]];
    
    NSArray *deleteArray = self.tableView.indexPathsForSelectedRows;
    
    NSArray *sortRows = [deleteArray sortedArrayUsingComparator:^NSComparisonResult(id obj1,id obj2){
        NSIndexPath *indexPath1 = obj1;
        NSIndexPath *indexPath2 = obj2;
        if (indexPath1.row > indexPath2.row) {
            return NO;
        }else{
            return YES;
        }
    }];
//    
//    for (NSIndexPath *indexPath in sortRows) {
//        DownLoadModel *model = self.dataArray[indexPath.row];
//        NSArray *arr = [DownLoadModel MR_findByAttribute:@"currentMp3Url" withValue:model.currentMp3Url];
//        for (DownLoadModel *model in arr) {
//            [model MR_deleteEntity];
//            [[NSFileManager defaultManager] removeItemAtPath:[NSHomeDirectory() stringByAppendingFormat:@"/Documents/%@",[model.currentMp3Url MD5Hash]] error:nil];
//        }
//        [[NSManagedObjectContext MR_defaultContext] MR_saveToPersistentStoreAndWait];
//        [self.dataArray removeObjectAtIndex:indexPath.row];
//    }
//    [self.tableView deleteRowsAtIndexPaths:sortRows withRowAnimation:UITableViewRowAnimationRight];
    
    self.tableView.allowsMultipleSelectionDuringEditing = NO;
    self.tableView.allowsSelectionDuringEditing = NO;
    [self.tableView setEditing:NO animated:YES];
    
    CGFloat y = self.view.bounds.size.height;
    [UIView animateWithDuration:0.2 animations:^{
        self.editView.frame = CGRectMake(0, y, self.view.bounds.size.width, 35);
    }];
    self.rightBarButtonItem2.enabled = YES;
}

- (void) editViewSetting{
    self.editView = [[UIView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height-64, self.view.bounds.size.width, 39)];
    self.editView.backgroundColor = [UIColor darkGrayColor];
    
    self.cancel = [[UIButton alloc] initWithFrame:CGRectMake(2, 2, self.view.bounds.size.width/3, 35)];
    self.cancel.backgroundColor = [UIColor grayColor];
    [self.cancel setTitle:@"取消" forState:UIControlStateNormal];
    [self.cancel addTarget:self action:@selector(cancelClick) forControlEvents:UIControlEventTouchUpInside];
    [self.editView addSubview:self.cancel];
    
    self.delete = [[UIButton alloc] initWithFrame:CGRectMake(self.view.bounds.size.width/3 * 2 -2,  2, self.view.bounds.size.width/3, 35)];
    self.delete.backgroundColor = [UIColor grayColor];
    [self.delete setTitle:@"删除" forState:UIControlStateNormal];
    [self.delete addTarget:self action:@selector(deleteClick) forControlEvents:UIControlEventTouchUpInside];
    [self.editView addSubview:self.delete];
    
    [self.view addSubview:self.editView];
}

#pragma mark - tableView创建
- (void)createTableView{
    self.tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.bounds.size.width, self.view.bounds.size.height-64) style:UITableViewStylePlain];
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.backgroundColor = [UIColor blackColor];
    self.tableView.showsVerticalScrollIndicator = NO;
    [self.tableView registerNib:[UINib nibWithNibName:@"DownLoadCell" bundle:nil] forCellReuseIdentifier:@"DownLoadCell"];
    
    [self.view addSubview:self.tableView];
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.dataArray.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    LeaderTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:@"DownLoadCell"];
    cell.backgroundView.backgroundColor = [UIColor clearColor];
    cell.selectionStyle = UITableViewCellSelectionStyleDefault;
    
    UIView *view = [[UIView alloc] initWithFrame:cell.frame];
    view.backgroundColor = [UIColor colorWithRed:0.3 green:0.3 blue:0.3 alpha:1];
    cell.selectedBackgroundView = view;
    
    DownLoadModel *model = self.dataArray[indexPath.row];
    
    cell.TitleLabe.text = model.topicTitle;
    cell.NameLabel.text = model.speakNickName;
    
    
    [cell.CoverImageView sd_setImageWithURL:[NSURL URLWithString:model.mainImageUrl] placeholderImage:[UIImage imageNamed: @"placehold_rec"]];
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (self.tableView.editing == YES) {
        return;
    }
    
    
    DownLoadModel *model = self.dataArray[indexPath.row];
    
    LeaderTableViewCell *cell = (LeaderTableViewCell *)[tableView cellForRowAtIndexPath:indexPath];
    CGFloat y = cell.frame.origin.y - tableView.contentOffset.y;
    [LZXHelper animationPlayWithUrl:model.mainImageUrl viewController:self leaderFrame:CGRectMake(8, y+64+7, 50, 50) newFrame:CGRectMake(self.view.bounds.size.width-30, 30, 6, 6)];
    
    [PlayerViewController sharePlayer].mainImageUrl = model.mainImageUrl;
    [PlayerViewController sharePlayer].topicTitle = model.topicTitle;
    [PlayerViewController sharePlayer].viewNum = model.viewNum;
    [PlayerViewController sharePlayer].avaImageUrl = model.avaImageUrl;
    [PlayerViewController sharePlayer].speakNickName = model.speakNickName;
    
    [[PlayerViewController sharePlayer] playWithUrl:model.currentMp3Url];
}


@end
